package main

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"github.com/go-basic/uuid"
	"github.com/gorilla/websocket"
)

var (
	DB *sql.DB

	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
)

type Result struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type JOBINFO struct {
	Name    string
	Uuid    string
	Stat    int
	Json    string
	Exp     string
	Created string
}

func checkFileIsExist(filename string) bool {
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return false
	}
	return true
}
func ERROR_202(w http.ResponseWriter, error_message string) {
	return_obj := Result{}
	return_obj.Code = 202
	return_obj.Message = error_message
	if return_str, _ := json.Marshal(return_obj); return_str != nil {
		_, _ = io.WriteString(w, string(return_str))
	} else {
		_, _ = io.WriteString(w, string("{}"))
	}
}

func ERROR_200(w http.ResponseWriter, data interface{}) {
	return_obj := Result{}
	return_obj.Code = 200
	return_obj.Data = data
	if return_str, _ := json.Marshal(return_obj); return_str != nil {
		_, _ = io.WriteString(w, string(return_str))
	} else {
		_, _ = io.WriteString(w, string("{}"))
	}

}

func INIT() {
	sqlit3, err := sql.Open("sqlite3", "./job.db")
	if err != nil {
		log.Fatal(err)
	}
	DB = sqlit3
	sql_table := `
CREATE TABLE IF NOT EXISTS "jobinfo" (
   "uuid" VARCHAR(64) PRIMARY KEY ,
	 "json" text not NULL,
	 "name" VARCHAR(64) not null,
	 "stat" int NULL default(0),
	 "exp" text,
   "created" TIMESTAMP default (datetime('now', 'localtime'))  
);`
	sqlit3.Exec(sql_table)
}

func (jobinfo *JOBINFO) expose_data(r *http.Request) error {
	body, err0 := ioutil.ReadAll(r.Body)
	if err0 != nil {
		log.Println(err0)
		return err0
	}
	err := json.Unmarshal(body, jobinfo)
	if err != nil {
		return err
	}
	return nil
}

func (jobinfo *JOBINFO) insert_row() error {
	stmt, err := DB.Prepare("insert into jobinfo (uuid,name,exp,json) values(?,?,?,?)")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(jobinfo.Uuid, jobinfo.Name, jobinfo.Exp, jobinfo.Json)
	if err != nil {
		return err
	}
	return nil
}

func (jobinfo *JOBINFO) start_row(stat int) error {
	stmt, err := DB.Prepare("update jobinfo set stat=? where uuid=?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(stat, jobinfo.Uuid)
	if err != nil {
		return err
	}
	return nil
}

func (jobinfo *JOBINFO) delete_row() error {
	stmt, err := DB.Prepare("delete from jobinfo where uuid= ?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(jobinfo.Uuid)
	if err != nil {
		return err
	}
	return nil
}

//创建jobjson文件
func (jobinfo *JOBINFO) create_job_json() error {
	jobinfo.Uuid = uuid.New()
	f, err := os.OpenFile("./job/"+jobinfo.Uuid+"_"+jobinfo.Name+".json", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) //linux 路径
	if err != nil {
		return err
	}
	defer f.Close() //资源必须释放,函数刚要返回之前延迟执行

	//格式化json
	var jsonbyte bytes.Buffer
	err1 := json.Indent(&jsonbyte, []byte(jobinfo.Json), "", "\t")
	if err1 != nil {
		return err1
	}
	jobinfo.Json = jsonbyte.String()
	_, err2 := f.WriteString(jobinfo.Json)
	fmt.Println("response Body", jobinfo.Json)
	if err2 != nil {
		return err2
	}
	return nil
}

func (jobinfo *JOBINFO) select_all_row() ([]interface{}, error) {
	var data []interface{}
	rows, err := DB.Query("SELECT uuid,json,stat,name,exp,created FROM jobinfo")
	defer func() {
		if rows != nil {
			rows.Close()
		}
	}()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		tempJobInfo := JOBINFO{}
		err = rows.Scan(&tempJobInfo.Uuid, &tempJobInfo.Json, &tempJobInfo.Stat, &tempJobInfo.Name, &tempJobInfo.Exp, &tempJobInfo.Created)
		if err != nil {
			return nil, err
		}
		data = append(data, tempJobInfo)
	}

	return data, nil
}
